﻿using System;
using System.Text;
using System.IO;

namespace SmartMovieTime
{
    interface ITxtTableRow
    {
        void LoadRow(string[] row);
    }

    class TxtTable <Row> : IDisposable
        where Row: ITxtTableRow, new()
    {
        private static char delimiter = ',';
        private bool disposed = false;

        
        private StreamReader readStream;

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public void Close()
        {
            Dispose();
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    readStream.Close();
                }

                disposed = true;
            }
        }

        public TxtTable()
        {
 
            readStream = null;
        }

        public static char Delimiter
        {
            get { return delimiter; }
            set { delimiter = value; }
        }

        public bool EndOfTable
        {
            get
            {
                if (readStream == null)
                    return true;
                else
                    return readStream.EndOfStream;
            }
        }

        public void LoadFromFile(string file)
        {
            readStream = new StreamReader(file, Encoding.Default);
        }

        public Row ReadNext()
        {
            string line = readStream.ReadLine();
            if (line != null && line.Length > 0)
            {
                string[] txtRow = line.Split(delimiter);
                Row row = new Row();
                row.LoadRow(txtRow);
                return row;
            }
            else
            {
                return default(Row);
            }
            
        }
    }
}
